<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>js类之检测</title>
</head>
<body>
  <ul>
    <li>可使用instanceof检测对象类型，是否在当前类或其父类的类型</li>
    <li>可使用isPrototypeOf检测对象是否在该类的原型链上</li>
  </ul>
  <script>
    function checkPrototype(obj, ctor) {
      if (!obj.__proto__) return false
      if (obj.__proto__ === ctor.prototype) return true
      return checkPrototype(obj.__proto__, ctor)
    }
    console.log('****************用class定义类****************')
    {
      class User {}
      class Admin extends User {}
      const admin = new Admin()
      console.log(admin instanceof Admin)               // true
      console.log(admin instanceof User)                // true
      console.log(checkPrototype(admin, Admin))         // true
      console.log(checkPrototype(admin, User))          // true
      console.log(Admin.prototype.isPrototypeOf(admin)) // true
      console.log(User.prototype.isPrototypeOf(admin))  // true
    }
    console.log('****************用function定义类****************')
    {
      function User() {}
      function Admin() {}
      Admin.prototype = Object.create(User.prototype)
      Object.defineProperty(Admin.prototype, 'constructor', {
        value: Admin,
        enumerable: false
      })
      const admin = new Admin()
      console.log(admin instanceof Admin)               // true
      console.log(admin instanceof User)                // true
      console.log(checkPrototype(admin, Admin))         // true
      console.log(checkPrototype(admin, User))          // true
      console.log(Admin.prototype.isPrototypeOf(admin)) // true
      console.log(User.prototype.isPrototypeOf(admin))  // true
    }
  </script>
</body>
</html>